const express = require("express");
const router = express.Router();
const routeHandler = require("../routes_handle/route");
const { CODE, Response } = require("../utils/response");
const { checkPermission } = require("../middleware/permission");

// 获取所有路由（树形结构）- 需要管理员权限
router.get("/admin/route/list", async (req, res, next) => {
  try {
    const routes = await routeHandler.getAllRoutes();
    res.status(CODE.SUCCESS).json(Response.success(routes));
  } catch (err) {
    next(err);
  }
});

// 添加路由 - 需要管理员权限
router.post(
  "/admin/route/add",
  checkPermission("route:add"),
  async (req, res, next) => {
    try {
      const result = await routeHandler.addRoute(req.body);
      res.status(CODE.SUCCESS).json(Response.success(result, "路由添加成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 更新路由 - 需要管理员权限
router.post(
  "/admin/route/update",
  checkPermission("route:edit"),
  async (req, res, next) => {
    try {
      const FId = req.body.FId;

      await routeHandler.updateRoute(FId, req.body);
      res.status(CODE.SUCCESS).json(Response.success(null, "路由更新成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 删除路由 - 需要管理员权限
router.post(
  "/admin/route/delete",
  checkPermission("route:delete"),
  async (req, res, next) => {
    try {
      const FId = req.body.FId;
      await routeHandler.deleteRoute(FId);
      res.status(CODE.SUCCESS).json(Response.success(null, "路由删除成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 获取角色拥有的路由 - 需要管理员权限
router.get("/admin/route/role", async (req, res, next) => {
  try {
    const routes = await routeHandler.getRoleRoutes(req.query.FRoleId);
    res.status(CODE.SUCCESS).json(Response.success(routes));
  } catch (err) {
    next(err);
  }
});

// 更新角色路由权限 - 需要管理员权限
router.post(
  "/admin/route/role/update",
  checkPermission("route:edit"),
  async (req, res, next) => {
    try {
      const { FRoleId, FRouteIds } = req.body;
      await routeHandler.updateRoleRoutes(FRoleId, FRouteIds);
      res
        .status(CODE.SUCCESS)
        .json(Response.success(null, "角色路由权限更新成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 获取当前用户的路由（用于前端动态路由）
router.get("/user/route/menu", async (req, res, next) => {
  try {
    const routes = await routeHandler.getUserRoutes(req.user.userId);
    res.status(CODE.SUCCESS).json(Response.success(routes));
  } catch (err) {
    next(err);
  }
});

module.exports = router;
